var express = require('express');
var router = express.Router();
var User = require('../models/users')


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
// 登录
router.post('/login', function(req, res, next) {
 var param = {
   userName:req.body.userName,
   userPwd:req.body.userPwd
 }
 User.findOne(param, function(err, doc){
   if (err) {
    res.json({
      status:'1',
      msg:err.message
    })
   }else{
    if(doc){
      // maxAge存一个小时
      res.cookie("userId", doc.userId, {
        path: '/',
        maxAge:1000*60*60
      })
      res.cookie("userName", doc.userName, {
        path: '/',
        maxAge:1000*60*60
      })
      // req.session.user = doc
      res.json({
        status: '0',
        msg: '',
        result: {
          userName: doc.userName
        }
      })
    }else{
      res.json({
        status: '1',
        msg: '用户名或密码不对',
      })
    }
   }
    
 })
});

// 登出接口
//  maxAge:-1清空记录
router.post('/logout', function(req,res,next) {
  res.cookie('userId','',{
    path: '/',
    maxAge:-1
  })
  res.json({
    status: '0',
    msg: '',
    result: ''
  })
});
router.get('/checkLogin', function(req,res,next){
  if(req.cookies.userId) {
    res.json({
      status: '0',
      msg: '',
      result: req.cookies.userName || ''
    });
  }else{
    res.json({
      status: '1',
      msg: '未登录',
      result: ''
    });
  }
});
// 购物车列表
router.get('/cartList',function(req,res,next){
  var userId = req.cookies.userId;
  User.findOne({userId:userId},function(err,doc){
  // 504 拼错了doc
  // 500 语法错误
    if(err){
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      if (doc) {
        res.json({
          status: '0',
          msg:'',
          result:doc.cartList
        })
      }
    }
  })
})
// 删除商品
router.post('/delCart', function(req, res, next){
  var userId = req.cookies.userId
  var productId = req.body.productId
  User.update({
    userId:userId
  },{
    $pull:{
      'cartList':{
        'productId':productId
      }
    }
  },function(err,doc){
    if(err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      res.json({
        status: '0',
        msg: '删除成功',
        result:''
      })
    }
  })
})
// 购物车修改
router.post('/cartEdit',function(req, res, next) {
  var userId = req.cookies.userId,
      productId = req.body.productId,
      checked = req.body.checked,
      productNum = req.body.productNum;
      console.log(productId,checked,productNum)
  User.update({
    "userId":userId,
    "cartList.productId":productId
  },{
    "cartList.$.productNum": productNum,
    "cartList.$.checked": checked
  },function (err, doc) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      res.json({
        status: '0',
        msg: '',
        result: doc
      })
    }
  })
})
// 购物车全选
router.post('/editCheckAll',function(req, res, next) {
  var userId = req.cookies.userId,
      checkAll = req.body.checkAll ? '1' : '0'
  User.findOne({'userId':userId}, function(err,user){
    if (err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if (user) {
        user.cartList.forEach((item) => {
          item.checked = checkAll
        })
        user.save(function(err1,doc){
          if (err1) {
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          } else {
            res.json({
              status: '0',
              msg: '',
              result: ''
            })
          }
        })
      }
    }
  })
})
// 获取地址列表
router.get('/getAddressList',function(req, res, next) {
  var userId = req.cookies.userId;
  User.findOne({'userId':userId},function(err, user){
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if(user) {
        res.json({
          status: '0',
          msg: '',
          result: user.addressList
        })
      }
    }
  })
})
// 新增地址
router.post('/addAddress', function(req, res, next){
  var userId = req.cookies.userId;
  User.findOne({'userId':userId},function(err, user){
    if(err) {
      res.json({
        status: '1',
        msg: err.message,
        result: ''
      })
    } else {
      if(user) {
        // 获取最新一条Id
        var lastAddressIndex = user.addressList.length - 1;
        var lastAddressId = user.addressList[lastAddressIndex].addressId * 1 + 1
        console.log(lastAddressId)
        var addressDoc = {
          'addressId': lastAddressId,
          'userName': req.body.reciveName,
          'streetName': req.body.reciveAddress,
          'tel': req.body.reciveTel,
          'postCode': req.body.reciveCode,
          "isDefault": false
        }
        user.addressList.push(addressDoc)
        user.save(function(err1,doc){
          if(err1) {
            res.json({
              status: '1',
              msg: err.message,
              result: ''
            })
          }else{
            res.json({
              status: '0',
              msg: '新增成功',
              result: doc
            })
          }
        })
      }
    }
  })
})
// 删除地址
router.post('/delAddress', function(req, res, next){
  var userId = req.cookies.userId
  var addressId = req.body.addressId
  User.update({
    userId: userId
  },{
    $pull: {
      'addressList':{
        'addressId': addressId
      }
    }
  },function(err, doc) {
    if(err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      res.json({
        status: '0',
        msg: '删除成功',
        result:''
      })
    }
  })
})
module.exports = router;
